<?php

namespace frontend\components;

use Yii;
use yii\web\Response;
use yii\helpers\Inflector;
use frontend\filters\AppBearerAuth;
use yii\filters\AccessControl;
use yii\filters\Cors;
use yii\helpers\ArrayHelper;

class Controller extends \yii\rest\Controller {

    public $serializer = [
        'class' => 'yii\rest\Serializer',
        'collectionEnvelope' => 'items',
        'linksEnvelope' => 'links',
        'metaEnvelope' => 'meta',
    ];

    /**
     * 处理Auth授权验证行为 & 设置返回format
     * @see behaviors
     * 1:QueryParamAuth 验证方式
     * ['authenticator']=>['class' => QueryParamAuth::className(),//'tokenParam' => 'token']
     * 2:ComopositeAuth 混合认证(authMethods 中的每一个元素都应该是 一种 认证方式的类或者一个 配置数组)
     * ['authenticator']=>['class' => CompositeAuth::className(),'authMethods' => [HttpBearerAuth::className(),QueryParamAuth::className()]]
     * @current use HttpBearer
     * @return $behaviors
     */
    public function behaviors() {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => AppBearerAuth::className(),
        ];
        $behaviors['contentNegotiator']['formats'] = [
            'application/json' => Response::FORMAT_JSON,
        ];
        if ($this->rules() !== null) {
            $behaviors['access'] = [
                'class' => AccessControl::className(),
                'rules' => $this->rules(),
            ];
        }
        return ArrayHelper::merge([
            'corsFilter' => [
                'class' => Cors::className(),
            ]
        ], $behaviors);
    }

    /**
     * @inheritdoc
     */
    protected function rules() {
        return null;
    }

    /**
     * {@inheritdoc}
     */
    protected function verbs() {
        return [
            'index' => ['GET', 'HEAD'],
            'view' => ['GET', 'HEAD'],
            'create' => ['POST'],
            'update' => ['PUT', 'PATCH'],
            'delete' => ['DELETE'],
        ];
    }

    /**
     * 记录日志
     */
    public static function log($prefix, $content) {
        $message = Inflector::id2camel($prefix);
        Yii::info($message);
        Yii::info($content);
    }

    /**
     * 获取当前登录用户
     */
    public function getUser() {
        return Yii::$app->user->identity;
    }

    /**
     * 获取当前登录用户ID
     */
    public function getUid() {
        return $this->token->user_id;
    }

    /**
     * 显示flash信息
     * @param $message 信息显示内容
     * @param string $extras 信息显示类型, ['info', 'success', 'error', 'warning']
     * @param null $code 跳转地址
     * @return Response
     */
    public static function error($message, $extras = null, $code = 418) {
        if (!empty($extras)) {
            $append = '';
            if (is_string($extras)) {
                $append = $extras;
            } elseif (is_array($extras)) {
                $append = array_shift($extras);
            } else {
                $append = print_r($extras, true);
            }
            $message .= ': ' . $append;
        }
        throw new \yii\web\HttpException($code, $message);
    }

    /**
     * 显示flash信息
     * @param $message 信息显示内容
     * @param string $extras 信息显示类型, ['info', 'success', 'error', 'warning']
     * @param null $code 跳转地址
     * @return Response
     */
    public static function warning($message, $extras = null, $code = 419) {
        if (!empty($extras)) {
            $append = '';
            if (is_string($extras)) {
                $append = $extras;
            } elseif (is_array($extras)) {
                $append = array_shift($extras);
            } else {
                $append = print_r($extras, true);
            }
            $message .= ': ' . $append;
        }
        throw new \yii\web\HttpException($code, $message);
    }

    /**
     * 显示flash信息
     * @param $message 信息显示内容
     * @param string $extras 信息显示类型, ['info', 'success', 'error', 'warning']
     * @param null $code 跳转地址
     * @return Response
     */
    public static function login($message, $extras = null, $code = 419) {
        if (!empty($extras)) {
            $append = '';
            if (is_string($extras)) {
                $append = $extras;
            } elseif (is_array($extras)) {
                $append = array_shift($extras);
            } else {
                $append = print_r($extras, true);
            }
            $message .= ': ' . $append;
        }
        throw new \yii\web\HttpException($code, $message);
    }

}
